<?php
/**
 * 
 * 状态静态类
 * @author will
 *
 */
class Status {
	static public $last_insert_id = 0;
	
	static public function getLastOne($uin) {
		$Db = loadDB();
		
		$list = $Db->getOne("SELECT * FROM `status` WHERE `uin` = {$uin} ORDER BY `id` DESC LIMIT 1");
		//解析单条回复
		if(!empty($list['reply'] )) {
			$list['reply'] = unserialize($list['reply']);
		}
		return $list;
	}
	
	/**
	 * 获取心情列表
	 * @param <int> $uin
	 * @param <int> $offset
	 * @param <int> $limit
	 */
	static public function getList($uin , $offset = 0 , $limit = 10) {
		$Db = loadDB();
		
		$list = $Db->getAll("SELECT * FROM `status` WHERE `uin` = {$uin} ORDER BY `id` DESC LIMIT {$offset} , {$limit}");
		//解析回复
		//print_r($list);
		foreach($list as $k => $row) {
			$list[$k]['reply'] = empty($row['reply']) ? array() : unserialize($row['reply']);
		}
		
		return $list;
	}
	
	/**
	 * 发表心情
	 * @param <int> $uin
	 * @param <string> $content
	 */
	static public function add($uin , $content) {
		$Db = loadDB();
		
		$id = $time = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();
		
		// 写入数据
		$insert_data = array(
			'uin' => $uin,
			'id' => $id,
			'content' => $content,
			'reply' => '',
			'time' => $time,
		);
		$success = $Db->doInsert('status' , $insert_data);
		
		if(!$success) {
			return 201;
		}
		
		self::$last_insert_id = $id;
		return 0;
	}
	
	/**
	 * 删除状态
	 * @param <int> $uin
	 * @param <int> $id
	 */
	static public function delete($uin , $id) {
		$Db = loadDB();
		
		// 写入数据
		$success = $Db->query("DELETE FROM `status` WHERE `uin` = {$uin} AND `id` = {$id}");
		
		return $success ? 0 : 202;
	}
	/**
	 * 获取单条心情
	 * @param <int> $uin
	 * @param <int> $id
	 */
	static public function getOneStatus($uin , $id) {
		$Db = loadDB();
		
		$list = $Db->getOne("SELECT * FROM `status` WHERE `uin` = {$uin} AND `id` = {$id}");
		//解析单条回复
		$list['reply'] = empty($list['reply']) ? array() : unserialize($list['reply']);
		return $list;
	}
	/**
	 * 快速回复心情
	 * @param <int> $others_uin
	 * @param <int> $uin
	 * @param <int> $id
	 * @param <string> $content
	 */
	static public function getUpSend($others_uin , $uin , $id , $content,$org_status = false) {
		$Db = loadDB();
		
		// 取原数据
		if(empty($org_status)) {
			$status = self::getOneStatus($others_uin , $id);
			if(empty($status)) {
				return 203;	// 该信息不存在
			}
		} else {
			$status = $org_status;
		}
		//print_r($id);
		$time = time();
		$status['reply'][] = array('uin' => $uin , 'content' => $content , 'time' => $time);
		
		// 写入数据
		$update_data = array(
			'reply' => serialize($status['reply']),
		);
		$success = $Db->doUpdate('status' , $update_data , "`uin` = {$others_uin} AND `id` = {$id}");

		return $success ? 0 : 502;
	}
}


# end of script
